﻿using AduSkin.Controls.Metro;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using HsServerHa.Core;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using Microsoft.Win32;
using System.Management;
using System.Threading;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// AddMultipleCard.xaml 的交互逻辑
    /// </summary>
    public partial class AddMultipleCard : UserControl
    {
        public AddMultipleCard()
        {
            InitializeComponent();
            InitData();
        }

        private List<NetWorkCardInfoEntity> remoteList = new List<NetWorkCardInfoEntity>();
        public async Task InitData()
        {
            var adapterList = NetWorkHelper.GetNetworkInfo();
            foreach (var adapter in adapterList)
            {
                string Name = adapter.Name;
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = Name;
                CurrNetWorkName.Items.Add(cbi);
            }
            if (App.isMaster != null)
            {
                //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
                //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);

                var masterList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var masterFirst = masterList.FirstOrDefault();
                var masterPath = "";
                if (masterFirst == null)
                {
                    AduMessageBoxs.Show("系统设置错误！");
                    return;
                }
                if (App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(masterFirst.SlaveIP))
                    {
                        AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                        return;
                    }
                    masterPath = $"http://{masterFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                }
                else
                {
                    masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }
                var list = await HttpHelpers.Get<HttpResponseResultModel<List<NetWorkCardInfoEntity>>>($"{masterPath}{ConfigurationManager.AppSettings["getRemoteCardInfo"]?.ToString() ?? "getRemoteCardInfo"}");
                if (list == null || !list.IsSuccess)
                {
                    AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                }
                if (list.BackResult == null || list.BackResult?.Count == 0)
                {
                    return;
                }
                remoteList = list?.BackResult ?? new List<NetWorkCardInfoEntity>();
                foreach (var item in list?.BackResult)
                {
                    string Name = item.CardName;
                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Content = Name;
                    RemoteNetWorkName.Items.Add(cbi);
                }
            }

        }

        /// <summary>
        /// 原MAC
        /// </summary>
        public string OriginalMAC { get; set; }

        private string GetRandMac()
        {           
            var random = new Random();
            var buffer = new byte[6];
            random.NextBytes(buffer);
            buffer[0] &= 0b11111110;
            buffer[0] |= 0b00000010;
            var result = string.Concat(buffer.Select(x => string.Format("{0}-", x.ToString("X2"))).ToArray());
            return result.TrimEnd('-');
        }
        private void btn_MacRand_Click(object sender, RoutedEventArgs e)
        {
            this.MAC.Text=GetRandMac();
        }
       
       
        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(CurrNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("当前网卡未设置！");
                return;
            }
            if (string.IsNullOrEmpty(RemoteNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("远程网卡未设置！");
                return;
            }
            if (string.IsNullOrEmpty(CurrIP.Text))
            {
                AduMessageBoxs.Show("当前网卡IP不能为空！");
                return;
            }
            if (!NetWorkHelper.IsStaticIP(CurrIP.Text))
            {
                AduMessageBoxs.Show($"请将你的IP（{CurrIP.Text}）固定！");
                return;
            }
            if (string.IsNullOrEmpty(RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("当前网卡IP不能为空！");
                return;
            }
            if (!NetWorkHelper.ValidateMask(SubnetMask.Text))
            {
                AduMessageBoxs.Show("子网掩码格式不正确");
                return;
            }
            if (!NetWorkHelper.ValidateIpAddress(CurrIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的当前IP");
                return;
            }
            if (!NetWorkHelper.ValidateIpAddress(RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的远程IP");
                return;
            }

            if (!NetWorkHelper.ValidateIpAddress(ReferIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的参考IP");
                return;
            }
            else
            {
                if (!NetWorkHelper.IsPingIP(ReferIP.Text))
                {
                    AduMessageBoxs.Show("请输入合法的参考IP");
                    return;
                }
            }
            if (!NetWorkHelper.ValidateIpAddress(VirtuallyIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的虚拟IP");
                return;
            }
            if (NetWorkHelper.IsPingIP(VirtuallyIP.Text))
            {
                AduMessageBoxs.Show("该虚拟IP已使用，请换一个IP");
                return;
            }
            if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(CurrIP.Text, RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("请选择同网段IP！");
                return;
            }
            if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(CurrIP.Text, VirtuallyIP.Text))
            {
                AduMessageBoxs.Show("当前IP和虚拟IP请选择同网段IP！");
                return;
            }

            var sql = $@"select * from MultipleNetworkCardManage  ";
            var netWorkDt = DbHelperSQLite.Query(sql)?.Tables?[0];
            if (netWorkDt.Rows.Count >= 3)
            {
                AduMessageBoxs.Show("网卡数量已经到达上限！");
                LoggerHelper.Warn("添加多网卡-主从未联机，请检查后再设置！", "多网卡设置");
                return;
            }

            var paramStr = new MultipleNetworkCardManageEntity()
            {
                CurrIP = RemoteNetWorkIP.Text,
                RemoteIP = CurrIP.Text,
                NetworkCardName = RemoteNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                SubnetMask = SubnetMask.Text,
                Gateway = Gateway.Text,
                DNS1 = DNS1.Text,
                DNS2 = DNS2.Text,
                MAC = MAC.Text,
                CurrentMAC = CurrentMAC.Text,
                RemoteMAC = RemoteMAC.Text,
                IsSyncMAC = IsSyncMAC.IsChecked.Value,
                VirtuallyIP = VirtuallyIP.Text,
                IsEnable = IsEnable.Text,
                ReferIP = ReferIP.Text,
                IsMaster = App.isMaster.Value ? "否" : "是",
                ProgramKey = GeneratePrimaryKeyIdHelper.GetPrimaryKeyId().ToString(),
                CreateTime = DateTime.Now.ToString()
            };
            if (App.isMaster != null)
            {
                //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
                //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);

                var masterList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var masterFirst = masterList.FirstOrDefault();
                var masterPath = "";
                if (App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(masterFirst.SlaveIP))
                    {
                        AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                        LoggerHelper.Error("添加多网卡-主从未联机，请检查后再设置！", "多网卡设置");
                        return;
                    }
                    masterPath = $"http://{masterFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }
                else
                {
                    masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }


                var result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>($"{masterPath}{ConfigurationManager.AppSettings["AddMulttipRemoteCardInfo"]?.ToString() ?? "AddMulttipRemoteCardInfo"}", JsonConvert.SerializeObject(paramStr));
                if (result == null)
                {
                    AduMessageBoxs.Show("系统API异常，请检查后再设置！");
                    LoggerHelper.Error("添加多网卡-系统API异常，请检查后再设置！", "多网卡设置");
                    return;
                }
                if (result.IsSuccess)
                {
                    var i = SQLiteHelper.ExecuteSql($"insert into MultipleNetworkCardManage (ProgramKey,CurrIP,NetworkCardName,RemoteIP,SubnetMask,Gateway,DNS1,DNS2,MAC,CurrentMAC,RemoteMAC,VirtuallyIP,ReferIP,IsMaster,IsEnable,CreateTime,IsSyncMAC)" +
                                                                       $" values('{paramStr.ProgramKey}','{CurrIP.Text}','{CurrNetWorkName.Text}','{RemoteNetWorkIP.Text}','{paramStr.SubnetMask}','{paramStr.Gateway}','{paramStr.DNS1}','{paramStr.DNS2}','{paramStr.MAC}','{paramStr.CurrentMAC}','{paramStr.RemoteMAC}','{paramStr.VirtuallyIP}','{paramStr.ReferIP}','{(App.isMaster.Value ? "是" : "否")}','{paramStr.IsEnable}','{DateTime.Now.ToString()}',{paramStr.IsSyncMAC})");


                    if (i >= 0)
                    {
                        AduMessageBoxs.Show("设置成功！");

                        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新多网卡数据"), "RefreshNetworkCard");

                        LoggerHelper.SetInfo($"添加成功->{JsonConvert.SerializeObject(paramStr)}", "多网卡设置");
                        var control = this.Parent as ContentControl;
                        Window win = Window.GetWindow(control);
                        var title = win?.Title;
                        if (title != null)
                        {
                            if (title != "HsServerHa")
                            {
                                win.Close();
                            }
                        }

                        ////修改MAC地址

                        //if (IsSyncMAC.IsChecked.Value)
                        //{
                        //    //更改网卡MAC地址，网卡状态为启用时才会生效
                        //    if (PhysicalAddress.TryParse(MAC.Text, out PhysicalAddress? mac))
                        //    {
                        //        var currNetWorkName = NetWorkHelper.GetAdapterByName(CurrNetWorkName.Text);
                        //        var remoteNetWorkName = RemoteNetWorkName.Text;
                        //        string macAddress = MAC.Text;
                        //        Task.Run(async () => SetMacAddress(currNetWorkName.Description, remoteNetWorkName, macAddress, masterPath));
                        //    }

                        //}

                        return;
                    }
                    else
                    {
                        AduMessageBoxs.Show("设置失败！");
                        LoggerHelper.Error("添加多网卡-设置失败,本地新增失败！", "多网卡设置");
                    }
                }
                else
                {
                    AduMessageBoxs.Show("设置失败，请检查系统配置！");
                    LoggerHelper.Error("添加多网卡-设置失败，请检查系统配置！", "多网卡设置");
                    return;
                }
            }
            else
            {
                AduMessageBoxs.Show("系统异常，请检查后再设置！");
                LoggerHelper.Error("添加多网卡-系统异常，请检查后再设置！", "多网卡设置");
                return;
            }
        }

        private async void CurrNetWorkName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
            //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
            //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);
            var masterList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
            var masterFirst = masterList.FirstOrDefault();
            if (masterFirst == null)
            {
                return;
            }

            //var dataSet = DbHelperSQLite.Query("SELECT * FROM MultipleNetworkCardManage ", null);
            //DataTable dt = dataSet.Tables[0];
            //List<MultipleNetworkCardManageEntity> list = DataHelpers.ConvertToModel<MultipleNetworkCardManageEntity>(dt);
            var list = SQLiteHelper.Table<MultipleNetworkCardManageEntity>().ToList();


            string content = CurrNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
            var adapter = NetWorkHelper.GetAdapterByName(content);
            if (adapter != null)
            {
                IPInterfaceProperties ip = adapter.GetIPProperties();
                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                var index = 0;
                foreach (UnicastIPAddressInformation item in ipCollection)
                {
                    if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        if (item.Address.ToString() == masterFirst.VirtuallyIP)
                        {
                            continue;
                        }
                        if (list.Any(x => x.VirtuallyIP == item.Address.ToString()))
                        {
                            continue;
                        }
                        this.CurrIP.Text = item.Address.ToString();
                        this.SubnetMask.Text = item.IPv4Mask.ToString();
                    }
                }
                Gateway.Text = NetWorkHelper.GetGateWay(ip);
                if (ip.DnsAddresses.Count > 0)
                {
                    DNS1.Text = ip.DnsAddresses[0].ToString();
                    if (ip.DnsAddresses.Count > 1)
                    {
                        DNS2.Text = ip.DnsAddresses[1].ToString();
                    }
                    else
                    {
                        DNS2.Text = "";
                    }
                }
                else
                {
                    DNS1.Text = "";
                    DNS2.Text = "";
                }
                PhysicalAddress pa = adapter.GetPhysicalAddress();
                byte[] bytes = pa.GetAddressBytes();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));
                    if (i != bytes.Length - 1)
                    {
                        sb.Append('-');
                    }
                }
                this.CurrentMAC.Text = sb.ToString();
                this.MAC.Text = sb.ToString();
                OriginalMAC = sb.ToString();
            }
        }

        private void RemoteNetWorkName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string content = RemoteNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
            var first = remoteList.FirstOrDefault(x => x.CardName == content);
            this.RemoteNetWorkIP.Text = first?.IP.ToString() ?? "";
            this.RemoteMAC.Text = first?.RemoteMac.ToString() ?? "";

        }

        public async Task SetMacAddress(string Description, string remoteNetWorkName, string MacAddress, string masterPath)
        {
            Thread.Sleep(5000);
            //同步远程网卡
            var postSetMACAddressResult = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>($"{masterPath}{ConfigurationManager.AppSettings["postSetMACAddress"]?.ToString() ?? "postSetMACAddress"}", JsonConvert.SerializeObject(new SetMACAddressEntity() { CardName = remoteNetWorkName, MAC = MacAddress }));
            //if (postSetMACAddressResult == null || !postSetMACAddressResult.IsSuccess)
            //{
            //    AduMessageBoxs.Show("同步远程网卡失败！");
            //    return;
            //}
            Thread.Sleep(5000);
            int setMacResult = NetWorkHelper.SetMacAddress(Description, MacAddress);
            if (setMacResult != 0)
            {
                //设置失败
                AduMessageBoxs.Show("设置MAC地址失败,请检查网卡是否为启用状态!");
            }
        }
    }
}
